/*
 * To change this template, choose Tools | Templates
 * and open the template in the editor.
 */

/*
 * MaestroArchivos.java
 *
 * Created on 20/02/2011, 02:49:54 PM
 */

package valida.Formularios;

import valida.Formularios.Carga.VentanaCarga;
import javax.swing.JOptionPane;
import javax.swing.table.DefaultTableModel;
import valida.Genericos.ThreadState;
import valida.Recursos.UtilBaseDatos;
import valida.beans.Archivo;
import valida.beans.Campo;

/**
 *
 * @author Andres Felipe
 */
public class MaestroArchivos extends javax.swing.JFrame {
    private Archivo archivoActual;

    /** Creates new form MaestroArchivos */
    public MaestroArchivos() {
        initComponents();
        postInitComponents();
    }

    /** This method is called from within the constructor to
     * initialize the form.
     * WARNING: Do NOT modify this code. The content of this method is
     * always regenerated by the Form Editor.
     */
    @SuppressWarnings("unchecked")
    // <editor-fold defaultstate="collapsed" desc="Generated Code">//GEN-BEGIN:initComponents
    private void initComponents() {

        lbNombreArchivo = new javax.swing.JLabel();
        jPanel1 = new javax.swing.JPanel();
        jScrollPane1 = new javax.swing.JScrollPane();
        tblCampos = new javax.swing.JTable();
        btnAdicionar = new javax.swing.JButton();
        btnRemover = new javax.swing.JButton();
        btnEditar = new javax.swing.JButton();
        txtNombreArchivo = new javax.swing.JTextField();
        btnCrearArchivo = new javax.swing.JButton();
        jPanel2 = new javax.swing.JPanel();
        btnAceptar = new javax.swing.JButton();
        btnCancelar = new javax.swing.JButton();
        jSeparator1 = new javax.swing.JSeparator();

        setDefaultCloseOperation(javax.swing.WindowConstants.EXIT_ON_CLOSE);

        lbNombreArchivo.setText("Nombre Archivo:");

        jPanel1.setBorder(javax.swing.BorderFactory.createTitledBorder("Campos"));

        tblCampos.setModel(new DefaultTableModel());
        tblCampos.setEnabled(false);
        jScrollPane1.setViewportView(tblCampos);

        btnAdicionar.setIcon(new javax.swing.ImageIcon(getClass().getResource("/valida/Recursos/Imagenes/Iconos/add.png"))); // NOI18N
        btnAdicionar.setEnabled(false);
        btnAdicionar.addActionListener(new java.awt.event.ActionListener() {
            public void actionPerformed(java.awt.event.ActionEvent evt) {
                btnAdicionarActionPerformed(evt);
            }
        });

        btnRemover.setIcon(new javax.swing.ImageIcon(getClass().getResource("/valida/Recursos/Imagenes/Iconos/remove.png"))); // NOI18N
        btnRemover.setEnabled(false);
        btnRemover.addActionListener(new java.awt.event.ActionListener() {
            public void actionPerformed(java.awt.event.ActionEvent evt) {
                btnRemoverActionPerformed(evt);
            }
        });

        btnEditar.setIcon(new javax.swing.ImageIcon(getClass().getResource("/valida/Recursos/Imagenes/Iconos/edit.png"))); // NOI18N
        btnEditar.setEnabled(false);

        javax.swing.GroupLayout jPanel1Layout = new javax.swing.GroupLayout(jPanel1);
        jPanel1.setLayout(jPanel1Layout);
        jPanel1Layout.setHorizontalGroup(
            jPanel1Layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
            .addGroup(javax.swing.GroupLayout.Alignment.TRAILING, jPanel1Layout.createSequentialGroup()
                .addContainerGap()
                .addComponent(jScrollPane1, javax.swing.GroupLayout.DEFAULT_SIZE, 307, Short.MAX_VALUE)
                .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED)
                .addGroup(jPanel1Layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
                    .addComponent(btnAdicionar)
                    .addComponent(btnRemover)
                    .addComponent(btnEditar)))
        );
        jPanel1Layout.setVerticalGroup(
            jPanel1Layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
            .addGroup(jPanel1Layout.createSequentialGroup()
                .addContainerGap()
                .addGroup(jPanel1Layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
                    .addComponent(jScrollPane1, javax.swing.GroupLayout.PREFERRED_SIZE, 166, javax.swing.GroupLayout.PREFERRED_SIZE)
                    .addGroup(jPanel1Layout.createSequentialGroup()
                        .addComponent(btnAdicionar)
                        .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.UNRELATED)
                        .addComponent(btnRemover)
                        .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.UNRELATED)
                        .addComponent(btnEditar)))
                .addContainerGap(javax.swing.GroupLayout.DEFAULT_SIZE, Short.MAX_VALUE))
        );

        btnCrearArchivo.setText("Crear Archivo");
        btnCrearArchivo.addActionListener(new java.awt.event.ActionListener() {
            public void actionPerformed(java.awt.event.ActionEvent evt) {
                btnCrearArchivoActionPerformed(evt);
            }
        });

        jPanel2.setBackground(new java.awt.Color(255, 255, 255));

        btnAceptar.setText("Aceptar");
        btnAceptar.setEnabled(false);
        btnAceptar.addActionListener(new java.awt.event.ActionListener() {
            public void actionPerformed(java.awt.event.ActionEvent evt) {
                btnAceptarActionPerformed(evt);
            }
        });

        btnCancelar.setText("Cancelar");
        btnCancelar.setEnabled(false);

        javax.swing.GroupLayout jPanel2Layout = new javax.swing.GroupLayout(jPanel2);
        jPanel2.setLayout(jPanel2Layout);
        jPanel2Layout.setHorizontalGroup(
            jPanel2Layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
            .addComponent(jSeparator1, javax.swing.GroupLayout.Alignment.TRAILING, javax.swing.GroupLayout.DEFAULT_SIZE, 404, Short.MAX_VALUE)
            .addGroup(javax.swing.GroupLayout.Alignment.TRAILING, jPanel2Layout.createSequentialGroup()
                .addContainerGap(196, Short.MAX_VALUE)
                .addComponent(btnAceptar)
                .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.UNRELATED)
                .addComponent(btnCancelar, javax.swing.GroupLayout.PREFERRED_SIZE, 94, javax.swing.GroupLayout.PREFERRED_SIZE)
                .addContainerGap())
        );

        jPanel2Layout.linkSize(javax.swing.SwingConstants.HORIZONTAL, new java.awt.Component[] {btnAceptar, btnCancelar});

        jPanel2Layout.setVerticalGroup(
            jPanel2Layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
            .addGroup(jPanel2Layout.createSequentialGroup()
                .addComponent(jSeparator1, javax.swing.GroupLayout.PREFERRED_SIZE, 10, javax.swing.GroupLayout.PREFERRED_SIZE)
                .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED)
                .addGroup(jPanel2Layout.createParallelGroup(javax.swing.GroupLayout.Alignment.BASELINE)
                    .addComponent(btnCancelar)
                    .addComponent(btnAceptar))
                .addContainerGap(javax.swing.GroupLayout.DEFAULT_SIZE, Short.MAX_VALUE))
        );

        javax.swing.GroupLayout layout = new javax.swing.GroupLayout(getContentPane());
        getContentPane().setLayout(layout);
        layout.setHorizontalGroup(
            layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
            .addComponent(jPanel2, javax.swing.GroupLayout.Alignment.TRAILING, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, Short.MAX_VALUE)
            .addGroup(javax.swing.GroupLayout.Alignment.TRAILING, layout.createSequentialGroup()
                .addContainerGap()
                .addComponent(jPanel1, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, Short.MAX_VALUE)
                .addContainerGap())
            .addGroup(layout.createSequentialGroup()
                .addContainerGap()
                .addComponent(lbNombreArchivo)
                .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED)
                .addComponent(txtNombreArchivo, javax.swing.GroupLayout.PREFERRED_SIZE, 195, javax.swing.GroupLayout.PREFERRED_SIZE)
                .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED)
                .addComponent(btnCrearArchivo, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, Short.MAX_VALUE)
                .addContainerGap())
        );
        layout.setVerticalGroup(
            layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
            .addGroup(layout.createSequentialGroup()
                .addContainerGap()
                .addGroup(layout.createParallelGroup(javax.swing.GroupLayout.Alignment.BASELINE)
                    .addComponent(lbNombreArchivo)
                    .addComponent(txtNombreArchivo, javax.swing.GroupLayout.PREFERRED_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.PREFERRED_SIZE)
                    .addComponent(btnCrearArchivo))
                .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED)
                .addComponent(jPanel1, javax.swing.GroupLayout.PREFERRED_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.PREFERRED_SIZE)
                .addGap(18, 18, 18)
                .addComponent(jPanel2, javax.swing.GroupLayout.PREFERRED_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.PREFERRED_SIZE))
        );

        pack();
    }// </editor-fold>//GEN-END:initComponents

    private void btnAdicionarActionPerformed(java.awt.event.ActionEvent evt) {//GEN-FIRST:event_btnAdicionarActionPerformed
        String NuevoCampo=JOptionPane.showInputDialog(this, "Ingrese el Nombre para el Nuevo Campo:", "Ingresar Campo", JOptionPane.QUESTION_MESSAGE);
        
        if (NuevoCampo != null) {
            Campo campoAdicionar=new Campo(NuevoCampo);
            archivoActual.addCampo(campoAdicionar);
            ModeloCampos.addRow(new Object[]{campoAdicionar});
        }
        NuevoCampo=null;
    }//GEN-LAST:event_btnAdicionarActionPerformed

    private void btnCrearArchivoActionPerformed(java.awt.event.ActionEvent evt) {//GEN-FIRST:event_btnCrearArchivoActionPerformed
        if (txtNombreArchivo.getText().trim().equalsIgnoreCase("")) {
            JOptionPane.showMessageDialog(this, "Debe ingresar un nombre de archivo para poder crearlo","Ingrese un nombre",JOptionPane.INFORMATION_MESSAGE);
            txtNombreArchivo.requestFocus();
        } else {
            txtNombreArchivo.setEnabled(false);
            this.setArchivo(new Archivo(txtNombreArchivo.getText().trim()));
            habilitarCreacionCampos(true);
        }
    }//GEN-LAST:event_btnCrearArchivoActionPerformed

    private void btnRemoverActionPerformed(java.awt.event.ActionEvent evt) {//GEN-FIRST:event_btnRemoverActionPerformed
        if(!(tblCampos.getSelectedRow()<0)){
            Campo campoRemover=(Campo)ModeloCampos.getValueAt(tblCampos.getSelectedRow(), 0);
            ModeloCampos.removeRow(tblCampos.getSelectedRow());
            archivoActual.removeCampo(campoRemover);
            campoRemover=null;
        }
    }//GEN-LAST:event_btnRemoverActionPerformed

    private void btnAceptarActionPerformed(java.awt.event.ActionEvent evt) {//GEN-FIRST:event_btnAceptarActionPerformed
       ThreadState thread = new ThreadState(){
            @Override
            public void run() {
                if(UtilBaseDatos.crearArchivo(archivoActual)){
                    this.setEstadoFinal(OK);
                }else{
                    this.setEstadoFinal(FAIL);
                }
            }
       };        
        if(new VentanaCarga(thread, "CreacionDeArchivoBD").getResultado().equalsIgnoreCase(ThreadState.OK)){
            new MaestroReglas().setVisible(true);
        }
       
    }//GEN-LAST:event_btnAceptarActionPerformed

    /**
    * @param args the command line arguments
    */
    public static void main(String args[]) {
        java.awt.EventQueue.invokeLater(new Runnable() {
            public void run() {
                new MaestroArchivos().setVisible(true);
            }
        });
    }

    // Variables declaration - do not modify//GEN-BEGIN:variables
    private javax.swing.JButton btnAceptar;
    private javax.swing.JButton btnAdicionar;
    private javax.swing.JButton btnCancelar;
    private javax.swing.JButton btnCrearArchivo;
    private javax.swing.JButton btnEditar;
    private javax.swing.JButton btnRemover;
    private javax.swing.JPanel jPanel1;
    private javax.swing.JPanel jPanel2;
    private javax.swing.JScrollPane jScrollPane1;
    private javax.swing.JSeparator jSeparator1;
    private javax.swing.JLabel lbNombreArchivo;
    private javax.swing.JTable tblCampos;
    private javax.swing.JTextField txtNombreArchivo;
    // End of variables declaration//GEN-END:variables

    
    DefaultTableModel ModeloCampos;

    private void postInitComponents() {

        if (ModeloCampos == null) {
            ModeloCampos = new DefaultTableModel();
            ModeloCampos.addColumn("Nombre del Campo");
        }

        //Adicionamos el TableModel
        tblCampos.setModel(ModeloCampos);
    }

    /**
     * Metodo para establecer un archivo actual, para permitir crear campos pertenecientes a este Archivo
     * @param archivo
     */
    private void setArchivo(Archivo archivo) {
        this.archivoActual=archivo;
    }
/**
 * Metodo para activar o desactivar el espacio para permitir al usuario crear los campos
 * @param Activos
 */
    private void habilitarCreacionCampos(boolean Activos) {
        tblCampos.setEnabled(Activos);
        btnAdicionar.setEnabled(Activos);
        btnEditar.setEnabled(Activos);
        btnRemover.setEnabled(Activos);
        btnAceptar.setEnabled(Activos);
        btnCancelar.setEnabled(Activos);
    }

}
